package com.ruoyi.web.controller.common;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.quartz.task.RyTask;
import com.ruoyi.system.domain.MingUserconfig;
import com.ruoyi.system.domain.Mynews;
import com.ruoyi.system.domain.MystockValueD;
import com.ruoyi.system.mapper.MingUserconfigMapper;
import com.ruoyi.system.mapper.MystockMapper;
import com.ruoyi.system.service.IMynewsService;
import com.ruoyi.system.service.impl.MystockValueDServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.google.code.kaptcha.Producer;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.web.client.RestTemplate;

import static org.springframework.web.servlet.function.EntityResponse.fromObject;

/**
 * 验证码操作处理
 * 
 * @author ruoyi
 */
@RestController
public class CaptchaController
{
    private static final Logger log = LoggerFactory.getLogger(CaptchaController.class);

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IMynewsService mynewsService;

    @Resource
    private RestTemplate restTemplate;

//    public static Map <String,String> weatherMap = new ConcurrentHashMap();

    @Autowired
    private MingUserconfigMapper mingUserconfigMapper;

    @Autowired
    private MystockMapper mystockMapper;

    @Autowired
    private MystockValueDServiceImpl mystockValueDService;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException
    {
        AjaxResult ajax = AjaxResult.success();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled)
        {
            return ajax;
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = RuoYiConfig.getCaptchaType();
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        }
        else if ("char".equals(captchaType))
        {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return AjaxResult.error(e.getMessage());
        }

        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }

    //

    /*@GetMapping("/getWeather")
    public AjaxResult getWeather(HttpServletResponse response) throws IOException
    {
        //要查询的地区编号
        String areaCode = "101190101";
        String rtString = "";
        if (RyTask.weatherMap.get(areaCode) == null) {
            //和风免费api，最多调用连续3天
            //String result = restTemplate.getForObject(
            //"https://devapi.qweather.com/v7/weather/3d?location=101190101&key=a36fae9e90b84c29b2b0b415779a8b72", String.class);

            //和风付费api，最大连续10天
            String result = restTemplate.getForObject(
                    "https://api.qweather.com/v7/weather/10d?location=101190101&key=3bec0920166d4b9383bdc5a8a29cb736", String.class);
            JSONObject param = JSONObject.parseObject(result);
            JSONArray json = JSONArray.parseArray(param.get("daily").toString());//JSONArray.fromObject(result); // 首先把字符串转成 JSONArray  对象
            if (json.size() > 0) {
                for (int i = 0; i < json.size(); i++) {
                    JSONObject job = json.getJSONObject(i);  // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                    rtString += (job.get("fxDate") + "-" + job.get("textDay"));  // 得到 每个对象中的属性值
                    rtString += ("--(" + job.get("tempMin") + "-");  // 得到 每个对象中的属性值
                    rtString += (job.get("tempMax") + "度)--(");  // 得到 每个对象中的属性值
                    rtString += (job.get("windDirDay") + "");  // 得到 每个对象中的属性值
                    rtString += (job.get("windScaleDay") + "级)\n");  // 得到 每个对象中的属性值
                }
            }
        } else {
            rtString = RyTask.weatherMap.get(areaCode);
        }
        Mynews mynews = new Mynews();
        if (RyTask.weatherMap.get("101190101")==null) {
            RyTask.weatherMap.put("101190101", rtString);
        }
        mynews.setComment(rtString);
        AjaxResult ajax = AjaxResult.success();
        return AjaxResult.success(mynews);
    }

    *//*@GetMapping("/getWeather2")
    public AjaxResult getWeather2(HttpServletResponse response) throws IOException
    {
        String result = restTemplate.getForObject(
                "https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/NanJing/2023-03-03/2023-03-013?key=UTMGKC8975WFQQTPXD4ELQKA3&lang=zh", String.class);
        JSONObject param = JSONObject.parseObject(result);
//        System.out.println(param.toString());
        JSONArray json = JSONArray.parseArray(param.get("days").toString());//JSONArray.fromObject(result); // 首先把字符串转成 JSONArray  对象

        String rtString = "";
        if(json.size()>0){
            for(int i=0;i<json.size();i++){
                JSONObject job = json.getJSONObject(i);  // 遍历 jsonarray 数组，把每一个对象转成 json 对象
//                System.out.print(job.get("datetime"));  // 得到 每个对象中的属性值
                rtString+=(job.get("datetime")+"-"+job.get("conditions"));  // 得到 每个对象中的属性值
//                rtString+=("--("+job.get("description")+")--");  // 得到 每个对象中的属性值
                rtString+="  气温:"+(((BigDecimal)job.get("temp")).subtract(new BigDecimal("33")).toString()+"(") ;  // 得到 每个对象中的属性值
                rtString+=(((BigDecimal)job.get("tempmin")).subtract(new BigDecimal("33")).toString()+"-") ;  // 得到 每个对象中的属性值
                rtString+=(((BigDecimal)job.get("tempmax")).subtract(new BigDecimal("33")).toString()+")\n") ;  // 得到 每个对象中的属性值
//                System.out.print((Long.valueOf(String.valueOf(job.get("tempmin").toString()))-33)+"-") ;  // 得到 每个对象中的属性值
//                System.out.print((Long.valueOf(String.valueOf(job.get("tempmax").toString()))-33)+")\n") ;  // 得到 每个对象中的属性值
            }
        }

        //增加新闻联播内容
        String allString = "";
        Mynews mynews = new Mynews();
        mynews = mynewsService.selectMynewsByMaxId();
        int zimujiange_num = 46;
        if (mynews.getComment().length()>zimujiange_num) {
            String tmp = processNews(mynews,"*");
            log.info(String.valueOf(tmp.length()));
            allString += getStringW(tmp,zimujiange_num);
            log.info(mynews.getComment());
            allString+="\n";
        }
        //增加10天 天气预报内容
        allString += rtString;
        allString+="\n";
        //增加stock
        MystockValueD mystockValueD = new MystockValueD();
        mystockValueD.setTsCode("'000001.SH','000002.SH'");
        mystockValueD.setTradeDate("20230303");
        List<MystockValueD> list = mystockValueDService.selectMystockValueDLists(mystockValueD);
        int stock_num = 20;
        String stockStr = "时间--代码--开盘--收盘--最高--最低--成交量\n";
        for (MystockValueD mystkD: list) {

            if (stock_num--<0) {
                break;
            }
//            stockStr +=mystkD.getTradeDate()+"-"+mystkD.getTsCode()+"-"+mystkD.getOpen()+"-"+mystkD.getClose()+"-"+mystkD.getHigh()+"-"+mystkD.getLow()+"-"+mystkD.getAmount()+"\n";
            stockStr +=mystkD.getTsCode()+"-"+mystkD.getOpen()+"-"+mystkD.getClose()+"-"+mystkD.getHigh()+"-"+mystkD.getLow()+"-"+mystkD.getAmount()+"\n";
        }
        allString += stockStr;
        //增加note
        MingUserconfig mingUserconfig = new MingUserconfig();
        mingUserconfig.setUserId(54l);
        String noteStr = "\n";
//        Mynews mynews = new Mynews();
        List<MingUserconfig> userConf = mingUserconfigMapper.selectMingUserconfigList(mingUserconfig);
        if (userConf!=null && userConf.size() ==1) {
//            int zimujiange_num = 46;
            MingUserconfig mingConf = userConf.get(0);
            if (mingConf.getNote().length()>zimujiange_num) {
                noteStr += getStringW(mingConf.getNote(),zimujiange_num);
            }
            else {
                noteStr +=mingConf.getNote();
            }
//            log.info(mynews.getComment());
        }
        allString += noteStr;

        mynews.setComment(allString);
        AjaxResult ajax = AjaxResult.success();
        return AjaxResult.success(mynews);
    }*//*

    @GetMapping("/getNew")
    public AjaxResult getNew(HttpServletResponse response) throws IOException
    {
        AjaxResult ajax = AjaxResult.success();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled)
        {
            return ajax;
        }

        Mynews mynews = mynewsService.selectMynewsByMaxId();
        int zimujiange_num = 20;
        if (mynews.getComment().length()>zimujiange_num) {
            String tmp = processNews(mynews,"*");
            log.info(String.valueOf(tmp.length()));
            mynews.setComment(getStringW(tmp,zimujiange_num));
            log.info(mynews.getComment());
        }
        return AjaxResult.success(mynews);
    }

    @GetMapping("/getNew3")
    public AjaxResult getNew3(HttpServletResponse response) throws IOException
    {
        AjaxResult ajax = AjaxResult.success();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled)
        {
            return ajax;
        }
        Mynews mynews = mynewsService.selectMynewsByMaxId();
        int zimujiange_num = 46;
        if (mynews.getComment().length()>zimujiange_num) {
            String tmp = processNews(mynews,"*");
            log.info(String.valueOf(tmp.length()));
            mynews.setComment(getStringW(tmp,zimujiange_num));
            log.info(mynews.getComment());
        }
        return AjaxResult.success(mynews);
    }

    @GetMapping("/getNote")
    public AjaxResult getNote(HttpServletResponse response) throws IOException
    {
        AjaxResult ajax = AjaxResult.success();
        Long userId = 54l;
        MingUserconfig mingUserconfig = new MingUserconfig();
        mingUserconfig.setUserId(userId);
        Mynews mynews = new Mynews();
        List<MingUserconfig> userConf = mingUserconfigMapper.selectMingUserconfigList(mingUserconfig);
        if (userConf!=null && userConf.size() ==1) {
            MingUserconfig mingConf = userConf.get(0);
            String tmp =mingConf.getNote();
            tmp = tmp.replaceAll("\r\n", "\n");
            tmp = tmp.replaceAll("\n", " ");
            int zimujiange_num = 46;
            if (mingConf.getNote().length()>zimujiange_num) {
                mynews.setComment(getStringW(tmp,zimujiange_num));
            }
            else {
                mynews.setComment(tmp);
            }
//            mynews.setComment(tmp);
            log.info(mynews.getComment());
        }
        return AjaxResult.success(mynews);
    }

    @GetMapping("/getStock")
    public AjaxResult getStock(HttpServletResponse response) throws IOException
    {
//        SysUser user = SecurityUtils.getLoginUser().getUser();
        AjaxResult ajax = AjaxResult.success();
        Long userId = 54l;
        MingUserconfig mingUserconfig = new MingUserconfig();
        mingUserconfig.setUserId(userId);
        String stocks = "";
        List<MingUserconfig> userConf = mingUserconfigMapper.selectMingUserconfigList(mingUserconfig);
        if (userConf!=null && userConf.size() ==1) {
            MingUserconfig mingConf = userConf.get(0);
            stocks = mingConf.getStock();
        }
        Map<String, Object> mystockValueDs = new HashMap<String, Object>(2);
        mystockValueDs.put("tradeDate","20230303");
        List codelist = new ArrayList();
        String [] mystocks = stocks.split(",");
        for (int i = 0; i < mystocks.length; i++) {
            codelist.add(mystocks[i]);
        }
        mystockValueDs.put("tsCodeList", codelist);
        List<MystockValueD> list = mystockValueDService.selectMystockValueDLists(mystockValueDs);
        Mynews mynews = new Mynews();
        int stock_num = 9;
        String stockStr = "----------代码--开盘--收盘--最高--最低--成交量\n";
        for (MystockValueD mystkD: list) {

            if (stock_num--<0) {
                break;
            }
//            stockStr +=mystkD.getTradeDate()+"-"+mystkD.getTsCode()+"-"+mystkD.getOpen()+"-"+mystkD.getClose()+"-"+mystkD.getHigh()+"-"+mystkD.getLow()+"-"+mystkD.getAmount()+"\n";
            stockStr +=mystkD.getTsCode()+"-"+mystkD.getOpen()+"-"+mystkD.getClose()+"-"+mystkD.getHigh()+"-"+mystkD.getLow()+"-"+mystkD.getAmount()+"\n";
        }
        mynews.setComment(stockStr);
//        if (mynews.getComment().length()>zimujiange_num) {
//            String tmp = processNews(mynews,"*");
//            log.info(String.valueOf(tmp.length()));
//            mynews.setComment(getStringW(stockStr,zimujiange_num));
//            log.info(mynews.getComment());
//        }
        return AjaxResult.success(mynews);
    }

    private String processNews(Mynews mynews,String jg) {
        String tmp = mynews.getComment();
        tmp = tmp.replaceAll("\r\n","");
        tmp = tmp.replaceAll("\n","");
        tmp = tmp.replaceAll("完整版","");
        tmp = tmp.replaceAll("《新闻联播》","");
        int a = 1;
        while (true) {
            tmp = tmp.replaceFirst("\\[视频\\]"," "+jg+" "+a++ +":");
            if (tmp.indexOf("[视频]")<0) {
                break;
            }
        }
        return tmp;
    }

    public static String substring(String orignal, int count)
            throws UnsupportedEncodingException {
        int tmpCount = count;
        // 原始字符不为null，也不是空字符串
        if (orignal != null && !"".equals(orignal)) {
            // 将原始字符串转换为GBK编码格式
            orignal = new String(orignal.getBytes(), "UTF-8");//
            // System.out.println(orignal);
            //System.out.println(orignal.getBytes().length);
            // 要截取的字节数大于0，且小于原始字符串的字节数
            if (count > 0 && count < orignal.getBytes("UTF-8").length) {
                StringBuffer buff = new StringBuffer();
                String All = "";
                char c;
                for (int i = 0; i < orignal.getBytes("UTF-8").length; i++) {
                    System.out.println(tmpCount);
                    c = orignal.charAt(i);
                    buff.append(c);
                    if (isChineseChar(c)) {
                        // 遇到中文汉字，截取字节总数减1
                        --tmpCount;
                    }
                    if (tmpCount ==1) {
                        All += buff.toString()+"\n";
                        buff = new StringBuffer();
                        tmpCount = count;
                    }
                }

                All += buff.toString()+"\n";
                buff = new StringBuffer();
                //   System.out.println(new String(buff.toString().getBytes("GBK"),"UTF-8"));
                return new String(buff.toString().getBytes(),"UTF-8");
            }
        }
        return orignal;
    }

    public static void main(String[] args) {
        String tmp = "5.【新春走基层】青春闪耀在“无名湖”;";
        System.out.println(getStringW(tmp,3));
    }

    static String tttt = "~。，、＇：∶；?‘’“”〝〞ˆˇ﹕︰﹔﹖﹑·¨….¸;！´？！～—ˉ｜‖＂〃｀@﹫¡¿﹏﹋﹌︴々﹟#﹩$﹠&﹪%*﹡﹢﹦﹤‐￣¯―﹨ˆ˜﹍﹎+=<\u00AD\u00AD＿_-\\ˇ~﹉﹊（）〈〉‹›﹛﹜『』〖〗［］《》〔〕{}「」【】︵︷︿︹︽_﹁﹃︻︶︸﹀︺︾ˉ﹂﹄︼";

    public static String getStringW(String value,int wide) {
        int valueLength = 0;
        String chinese = "[\u4e00-\u9fa5]";
        String all = "";
        for (int i = 0; i < value.length(); i++) {
            String temp = value.substring(i, i + 1);
//            System.out.println("---"+temp);
            if (temp.matches(chinese)||tttt.indexOf(temp)>=0) {
                valueLength += 2;
            } else {
                valueLength += 1;
            }
            all +=temp;
            if (valueLength>=wide) {
                all +="\n";
                valueLength = 0;
            }
        }
        System.out.println(all);
        return all;
    }



    *//**
     * 判断是否是一个中文汉字
     *
     * @param c
     *            字符
     * @return true表示是中文汉字，false表示是英文字母
     * @throws UnsupportedEncodingException
     *             使用了JAVA不支持的编码格式
     *//*
    public static boolean isChineseChar(char c)
            throws UnsupportedEncodingException {
        // 如果字节数大于1，是汉字
        // 以这种方式区别英文字母和中文汉字并不是十分严谨，但在这个题目中，这样判断已经足够了
        return String.valueOf(c).getBytes("UTF-8").length > 1;
    }*/
}
